package com.hn658.groupshare.group.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hn658.framework.dataaccess.pagination.GenericPage;
import com.hn658.groupshare.filemgmt.service.IValidator;
import com.hn658.groupshare.filemgmt.service.exception.ValidateException;
import com.hn658.groupshare.group.dao.db.IGroupInfoDbDao;
import com.hn658.groupshare.group.entity.GroupInfoEO;
import com.hn658.groupshare.group.service.IGroupInfoService;

/**
 * 
 * 群管理
 * @author ztjie
 * @date 2015-12-7 下午10:40:37
 * @since
 * @version
 */
@Service
public class GroupInfoServiceImpl implements IGroupInfoService,IValidator {
	
	//TODO 三天，待修改成后台配置常量参数
	private static final int EXPIRE_HOURS = 24 * 5;
	
	@Autowired
	private IGroupInfoDbDao groupInfoDbDao;

	@Override
	public GenericPage<GroupInfoEO> queryGroupsByParams(
			Map<String, Object> params, Integer limit, Integer start,
			String orderBy, boolean isAsc) {
		return groupInfoDbDao.selectByMap(params, limit, start, orderBy, isAsc);
	}

	@Override
	public void createGroupInfo(GroupInfoEO groupInfo) {
		groupInfo.setCreateTime(new Date());
		groupInfo.setLastUpdateTime(new Date());
		groupInfo.setIsDeleted(false);
		groupInfoDbDao.insert(groupInfo);
	}

	@Override
	public GroupInfoEO findGroupShareById(Long id) {
		return groupInfoDbDao.selectById(id);
	}

	@Override
	public void updateGroup(GroupInfoEO groupInfo) {
		groupInfoDbDao.update(groupInfo);
	}

	@Override
	public void updateExpireGroup() {
		
		List<GroupInfoEO> list = groupInfoDbDao.queryUnExpireGroupList();
		
		for (GroupInfoEO group : list) {
			
			Date expireTime = DateUtils.addHours(group.getCreateTime(), EXPIRE_HOURS); 
			
			//过期
			if(expireTime.before(new Date())){
				
				group.setExpireTime(expireTime);
				group.setLastUpdateTime(new Date());
				group.setIsDeleted(true);
				
				groupInfoDbDao.update(group);
			}
		}
	}

	@Override
	public boolean validateQrcode(String qrcodeText) throws ValidateException {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("qrcodeText", qrcodeText);
		params.put("isDeleted", false);
		
		List<GroupInfoEO> list = groupInfoDbDao.queryGroupList(params);
		if(list.size()>0)
			throw new ValidateException(ValidateException.QrcodeIsExsit);
		
		return true;
			
	}


}
